// 引入fastify和routes配置
const fastify = require("./app");
// 引入路由配置
const { routes, wsRoutes } = require("./routes");

// 注册路由

// registerRoutes(routes);
// fastify.register(require('./routes/example'));


// const fetch = require("cross-fetch");
// async function getPublicIP() {
//   try {
//     const response = await fetch('https://api.ipify.org?format=json');
//     const data = await response.json();
//     return data.ip;
//   } catch (error) {
//     console.error('Error fetching public IP:', error);
//     return 'localhost'; // 如果获取失败，退回到localhost
//   }
// }
// Register Swagger
async function registerSwagger(fastifyInstance, opts, next) {
  // const publicIP = await getPublicIP();
  // fastifyInstance.env.publicIP = publicIP;

  fastifyInstance.register(require('@fastify/swagger'), {
    swagger: {
      info: {
        title: 'fatify-service-template',
        description: 'API documentation',
        version: '1.0.0'
      },

      host: `${process.env.ENV_HOST}:${process.env.ENV_PORT}`,
      schemes: ['http'],
      consumes: ['application/json'],
      produces: ['application/json']
    }
  });

  fastifyInstance.register(require('@scalar/fastify-api-reference'), {
    routePrefix: '/docs',
  })

// // Register Swagger UI
// fastify.register(require('@fastify/swagger-ui'), {
//     routePrefix: '/docs',
//     uiConfig: {
//         docExpansion: 'full',
//         deepLinking: false
//     },
//     staticCSP: true,
//     transformStaticCSP: (header) => header,
//     exposeRoute: true
// });
  fastify.register(routes); // 不能用registerWs的方式，否则swager 不生效。
  next();
}
// 注册动态配置Swagger的插件
fastify.register(registerSwagger);


function registerWs(routes) {
  fastify.register(async function (fastify) {
    for (let k =0;k<routes.length;k++) {
      fastify.get(wsRoutes[k].url, { websocket: true }, wsRoutes[k].handler)
    }
  })
}
const websocket = require('@fastify/websocket');
// 注册websocket
fastify.register(websocket, {
  cors: true
})


registerWs(wsRoutes)

// 启动服务器
const start =  () => {
  fastify.listen({ port: fastify.env.ENV_PORT, host: '0.0.0.0' }, (err, address) => {
    if (err) {
      fastify.log.error(err);
      process.exit(1)
    }
  });
};

start();

